from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.mixins import CacheResponseMixin  #DRF扩展--> 缓存到Redis  RetrieveCacheResponseMixin,ListCacheResponseMixin

from .models import Area
from . import serializers


# Create your views here.
                    # DRF扩展Redis缓存 第二步
class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """获取所有省和获取单一 省及市"""
    pagination_class = None  # 禁用分页

    # 指定查询集
    # queryset = Area.objects.filter(parent=None)
    def get_queryset(self):
        """重写此方法动态指定查询集"""

        # 进行状态判断   ==> 判断是否为list查询全部
        if self.action == 'list':  # 如果当前是list行为
            return Area.objects.filter(parent=None)
        else:
            # 否则为retrieve
            return Area.objects.all()

    # 指定序列化器
    # serializer_class = serializers.AreaSerializer
    def get_serializer_class(self):
        """重写此方法动态指定序列化器"""
        # 进行状态判断   ==> 判断是否为list查询全部
        if self.action == 'list':
            return serializers.AreaSerializer
        else:
            # 否则为retrieve
            return serializers.SubsAreaSerializer